﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.Xml;
using System.IO;
using Newtonsoft.Json;

namespace wikisoft.onlineCoding.css
{
    public enum MessageType
    {
        warn,
        error
    }
    public class ValidateMessage
    {
        public MessageType type;
        public int index;
        public string line;
        public string message;
        public string selectorText;

        public ValidateMessage(MessageType t,int i,string m,string l,string s)
        {
            type = t;
            index = i;
            message = m;
            line = l;
            selectorText = s;
        }
    }
    public class ValidateResult
    {
        public List<ValidateMessage> results;
        public int totalCount = 0;
        public int errCount = 0;
        public int warnCount = 0;

        public ValidateResult()
        {
            results=new List<ValidateMessage>();
        }

        public void add(ValidateMessage mes)
        {
            results.Add(mes);
        }
    }
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class cssValidator : IHttpHandler
    {
        private int m_startLine = 0;
        private HttpContext m_context;
        private string m_cssText = "";
        private string m_callback = "";
        private int m_needWarning = 1; //1需要 0不需要

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            m_context = context;
            m_cssText = context.Request["text"];
            m_callback = context.Request["callback"];
            if (m_callback == null) m_callback = "";
            v(m_cssText, 0);
        }

        public void v(string srcText,int startLine)
        {
            m_startLine = startLine;
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            client.UseDefaultCredentials = true;
            client.DownloadStringAsync(createUrl("http://jigsaw.w3.org/css-validator/validator",srcText,"soap12","zh-cn",m_needWarning));
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        }

        private Uri createUrl(string urlNoQuery,string text, string output, string lang, int warning)
        {
            return new Uri(
                string.Concat(urlNoQuery,
                "?text=",
                text,
                "&output=",
                output,
                "&lang=",
                lang,
                "&warning=",
                warning)
                );
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            StringReader sr = new StringReader(e.Result);
            
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(e.Result);

            XmlNodeList errCountNodes = doc.GetElementsByTagName("m:errorcount");
            XmlNodeList wrnCountNodes = doc.GetElementsByTagName("m:warningcount");

            string errCount = "0";
            string wrnCount = "0";

            ValidateResult result = new ValidateResult();

            if (errCountNodes.Count != 0)
            {
                errCount = errCountNodes[0].InnerText;
            }
            if (wrnCountNodes.Count != 0)
            {
                wrnCount = wrnCountNodes[0].InnerText;
            }


            int index = 1;
            if (errCount != "0")
            {
                XmlNodeList errNodes = doc.GetElementsByTagName("m:error");
                foreach (XmlNode node in errNodes)
                {
                    string line = node.ChildNodes[0].InnerText;

                    int nline = int.Parse(line) + m_startLine;
                    line = nline.ToString();

                    string regular = node.ChildNodes[2].InnerText;
                    string mes = node.LastChild.InnerText;

                    ValidateMessage li = new ValidateMessage(MessageType.error,
            index,
            mes,
            line,
            regular);
                    result.add(li);

                    index++;
                }
            }

            if (wrnCount != "0")
            {
                XmlNodeList wrnNodes = doc.GetElementsByTagName("m:warning");
                foreach (XmlNode node in wrnNodes)
                {
                    string line = node.ChildNodes[0].InnerText;

                    int nline = int.Parse(line) + m_startLine;
                    line = nline.ToString();
                    string mes = node.ChildNodes[2].InnerText;
                    string regular = node.LastChild.InnerText;

                    ValidateMessage li = new ValidateMessage(MessageType.warn,
                        index,
            mes,
            line,
            regular);

                    result.add(li);

                    index++;
                }
            }

            result.errCount = Convert.ToInt32(errCount);
            result.warnCount=Convert.ToInt32(wrnCount);

            CreateResult(result);
        }

        private void CreateResult(ValidateResult result)
        {
            string jsonResult = JavaScriptConvert.SerializeObject(result);
            string output = "";

            if (m_callback != "")
            {
                output = string.Concat(m_callback, "(", jsonResult, ");");
            }
            else
            {
                output = jsonResult;
            }

            m_context.Response.Write(output);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
